<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>权限申请系统</title>
    <script>
        // 检查用户登录状态
        document.addEventListener('DOMContentLoaded', function() {
            fetch('/api/check-login')
                .then(response => response.json())
                .then(data => {
                    if (!data.loggedIn) {
                        // 未登录，重定向到登录页面
                        window.location.href = 'login.html';
                    } else {
                        // 已登录，根据角色控制导航
                        if (data.role !== 'admin') {
                            // 普通用户，隐藏服务器管理链接
                            const serverLink = document.querySelector('a[href="server-management.html"]');
                            if (serverLink) {
                            serverLink.parentElement.style.display = 'none';
                            }
                            // 隐藏TOTP设置链接
                            const totpLink = document.querySelector('a[href="/api/totp-setup"]');
                            if (totpLink) {
                                totpLink.parentElement.style.display = 'none';
                            }
                        }
                    }
                })
                .catch(error => {
                    console.error('检查登录状态失败:', error);
                    alert('检查登录状态失败，请刷新页面重试');
                });
        });
    </script>
    <link href="/node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        /* 全局样式 */
        :root {
            --primary-color: #165DFF;
            --secondary-color: #334155;
            --success-color: #00B42A;
            --danger-color: #F53F3F;
            --warning-color: #FF7D00;
            --light-color: #f7fafc;
            --dark-color: #1a202c;
            --border-color: #e2e8f0;
            --shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            --transition: all 0.3s ease;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f8fafc;
            color: var(--dark-color);
            line-height: 1.6;
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
            padding: 2rem;
        }

        /* 标题样式 */
        h1 {
            color: var(--primary-color);
            font-weight: 700;
            margin-bottom: 1.5rem;
            padding-bottom: 0.5rem;
            border-bottom: 3px solid var(--primary-color);
        }

        h2 {
            color: var(--dark-color);
            font-weight: 600;
            margin-bottom: 1rem;
        }

        /* 导航样式 */
        nav ul {
            display: flex;
            list-style: none;
            padding: 0;
            margin-bottom: 2rem;
            background-color: white;
            border-radius: 8px;
            box-shadow: var(--shadow);
            overflow: hidden;
        }

        nav li {
            margin: 0;
        }

        nav a {
            display: block;
            padding: 12px 20px;
            text-decoration: none;
            color: var(--secondary-color);
            font-weight: 500;
            transition: var(--transition);
        }

        nav a:hover {
            background-color: rgba(74, 108, 247, 0.1);
            color: var(--primary-color);
        }

        nav button {
            display: block;
            padding: 12px 20px;
            background: none;
            border: none;
            font-weight: 500;
            cursor: pointer;
            transition: var(--transition);
        }

        /* 卡片样式 */
        .card {
            border: none;
            border-radius: 12px;
            box-shadow: var(--shadow);
            transition: var(--transition);
            overflow: hidden;
        }

        .card:hover {
            box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
            transform: translateY(-5px);
        }

        .card-body {
            padding: 1.5rem;
        }

        .card-title {
            color: var(--primary-color);
            font-weight: 600;
            margin-bottom: 1rem;
        }

        /* 表单样式 */
        .form-label {
            font-weight: 500;
            color: var(--secondary-color);
            margin-bottom: 0.5rem;
        }

        .form-control,
        .form-select {
            padding: 12px 15px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            font-size: 1rem;
            transition: var(--transition);
        }

        .form-control:focus,
        .form-select:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(74, 108, 247, 0.1);
        }

        /* 按钮样式 */
        .btn {
            padding: 10px 20px;
            border-radius: 6px;
            font-weight: 500;
            transition: var(--transition);
        }

        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }

        .btn-primary:hover {
            background-color: #3a5bdb;
            border-color: #3a5bdb;
            transform: translateY(-2px);
        }

        .btn-success {
            background-color: var(--success-color);
            border-color: var(--success-color);
        }

        .btn-success:hover {
            background-color: #2f855a;
            border-color: #2f855a;
            transform: translateY(-2px);
        }

        .btn-outline-secondary {
            border-color: var(--border-color);
            color: var(--secondary-color);
        }

        .btn-outline-secondary:hover {
            background-color: var(--light-color);
            border-color: var(--secondary-color);
        }

        .btn-link {
            color: var(--danger-color);
            text-decoration: none;
        }

        .btn-link:hover {
            color: #c53030;
            text-decoration: none;
            background-color: rgba(229, 62, 62, 0.1);
        }

        /* 提示框样式 */
        .alert {
            border-radius: 8px;
            border: none;
            padding: 1rem;
        }

        .alert-success {
            background-color: rgba(56, 161, 105, 0.1);
            color: var(--success-color);
        }

        .alert-info {
            background-color: rgba(74, 108, 247, 0.1);
            color: var(--primary-color);
        }

        /* 其他样式 */
        .hidden {
            display: none;
        }

        .countdown {
            font-weight: bold;
            color: var(--danger-color);
        }

        code {
            background-color: var(--light-color);
            padding: 2px 6px;
            border-radius: 4px;
            font-family: monospace;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
            padding: 1rem;
        }

        nav ul {
            flex-direction: column;
        }

        nav li {
            width: 100%;
        }
    }

    /* 页脚样式 */
    footer {
        text-align: center;
        padding: 20px;
        margin-top: 50px;
        color: var(--secondary-color);
        font-size: 0.9rem;
        border-top: 1px solid var(--border-color);
    }
</style>
</head>
<body>
<div class="container py-5">
    <h1 class="mb-4">权限申请系统</h1>
    <nav>
        <ul style="list-style-type: none; padding: 0;">
            <li style="display: inline; margin-right: 20px;">
                <a href="#" style="text-decoration: none; color: #0066cc;">密码申请</a>
            </li>
            <li style="display: inline; margin-right: 20px;">
            <a href="server-management.html" style="text-decoration: none; color: #0066cc;">服务器管理</a>
        </li>
        <li style="display: inline; margin-right: 20px;">
            <a href="/api/totp-setup" style="text-decoration: none; color: #0066cc;">TOTP设置</a>
        </li>
            <li style="display: inline; margin-right: 20px;">
                <button id="logoutBtn" class="btn btn-link" style="text-decoration: none; color: #dc3545;">退出登录</button>
            </li>
        </ul>
    </nav>
    <script>
        // 退出登录功能
        document.getElementById('logoutBtn').addEventListener('click', function() {
            fetch('/api/logout', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 退出成功，重定向到登录页面
                    window.location.href = 'login.html';
                } else {
                    alert('退出登录失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('退出登录请求失败:', error);
                alert('退出登录失败，请重试');
            });
        });
    </script>

    <!-- 申请表单 -->
    <div id="applySection" class="card">
        <div class="card-body">
            <h2 class="card-title">权限申请</h2>
            <form id="applyForm">
                <div class="mb-3">
                    <label class="form-label">申请人</label>
                    <input type="text" class="form-control" id="applicant" readonly required>
                </div>
                <script>
                    // 获取当前登录用户信息并填充申请人字段
                    document.addEventListener('DOMContentLoaded', function() {
                        fetch('/api/check-login')
                            .then(response => response.json())
                            .then(data => {
                                if (data.loggedIn) {
                                    // 从会话中获取用户昵称（实际项目中可能需要单独接口）
                                    // 这里简化处理，假设在check-login接口返回昵称
                                    fetch('/api/user-info')
                                        .then(res => res.json())
                                        .then(userData => {
                                            if (userData.nickname) {
                                                document.getElementById('applicant').value = userData.nickname;
                                            }
                                        })
                                        .catch(error => {
                                            console.error('获取用户信息失败:', error);
                                        });
                                }
                            })
                            .catch(error => {
                                console.error('检查登录状态失败:', error);
                            });
                    });
                </script>
                <div class="mb-3">
                    <label class="form-label">申请账号</label>
                    <input type="text" class="form-control" id="accountName" value="qwer" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">目标主机</label>
                    <input type="text" class="form-control" id="targetHost" value="10.199.0.54" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">申请时长 (小时)</label>
                    <select class="form-select" id="duration">
                        <option value="1">1</option>
                        <option value="2" selected>2</option>
                        <option value="4">4</option>
                        <option value="8">8</option>
                        <option value="12">12</option>
                    </select>
                </div>
                <button type="submit" class="btn btn-primary">提交申请</button>
            </form>
        </div>
    </div>

    <!-- OTP验证 -->
    <div id="otpSection" class="card mt-4 hidden">
        <div class="card-body">
            <h2 class="card-title">OTP验证</h2>
            <p>请向管理员获取TOTP验证码</p>
            <form id="otpForm">
                <input type="hidden" id="requestId">
                <div class="mb-3">
                    <input type="text" class="form-control" id="otpCode" placeholder="输入OTP" required>
                </div>
                <button type="submit" class="btn btn-success" id="otpSubmitBtn">验证OTP</button>
            </form>
        </div>
    </div>

    <!-- 结果展示 -->
    <div id="resultSection" class="card mt-4 hidden">
        <div class="card-body">
            <h2 class="card-title">申请结果</h2>
            <div class="alert alert-success">
                <h4>申请成功!</h4>
                <p>账号: <span id="resultAccount"></span></p>
                <p>密码: <code id="resultPassword"></code></p>
                <p>过期时间: <span id="resultExpire"></span></p>
                <button class="btn btn-sm btn-outline-secondary mt-2" onclick="copyPassword()">复制密码</button>
            </div>
        </div>
    </div>

    <!-- 已有权限提示 -->
    <div id="existingSection" class="card mt-4 hidden">
        <div class="card-body">
            <h2 class="card-title">权限已存在</h2>
            <div class="alert alert-info">
                <p>该账号已有有效权限，可直接使用</p>
                <p>过期时间: <span id="existingExpire"></span></p>
                <p>当前密码: <span id="currentPWD"></span></p>
<!--                 <button class="btn btn-primary" onclick="location.reload()">重新申请</button>-->
            </div>
        </div>
    </div>
</div>

<script>
    // DOM元素
    const applySection = document.getElementById('applySection');
    const otpSection = document.getElementById('otpSection');
    const resultSection = document.getElementById('resultSection');
    const existingSection = document.getElementById('existingSection');

    // 申请表单提交
    document.getElementById('applyForm').addEventListener('submit', async (e) => {
        e.preventDefault();

        const response = await fetch('/api/apply', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                applicant: document.getElementById('applicant').value,
                accountName: document.getElementById('accountName').value,
                targetHost: document.getElementById('targetHost').value,
                duration: document.getElementById('duration').value
            })
        });

        const result = await response.json();
        console.log(result)

        if (result.error) {
            alert(`错误: ${result.error}`);
            return;
        }

        if (result.action === 'useExisting') {
            document.getElementById('existingExpire').textContent =
                new Date(result.expireTime).toLocaleString();
            document.getElementById('currentPWD').textContent =
                result.password;
            existingSection.classList.remove('hidden');
            applySection.classList.add('hidden');
            return;
        }

        document.getElementById('requestId').value = result.requestId;
        applySection.classList.add('hidden');
        otpSection.classList.remove('hidden');


    });

    // OTP验证表单提交
    document.getElementById('otpForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const submitBtn = document.getElementById('otpSubmitBtn');
        const originalText = submitBtn.textContent;
        submitBtn.disabled = true;
        submitBtn.textContent = '请稍后...';

        const response = await fetch('/api/verify', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                requestId: document.getElementById('requestId').value,
                otp: document.getElementById('otpCode').value
            })
        });

        const result = await response.json();

        if (result.error) {
            alert(`错误: ${result.error}`);
            return;
        }

        document.getElementById('resultAccount').textContent =
            document.getElementById('accountName').value;
        document.getElementById('resultPassword').textContent = result.password;
        document.getElementById('resultExpire').textContent =
            new Date(result.expireTime).toLocaleString();

        otpSection.classList.add('hidden');
        resultSection.classList.remove('hidden');
        submitBtn.disabled = false;
        submitBtn.textContent = originalText;
    });

    // 复制密码
    function copyPassword() {
        navigator.clipboard.writeText(
            document.getElementById('resultPassword').textContent
        ).then(() => {
            alert('密码已复制到剪贴板');
        });
    }
</script>
    <footer>
        权限管理工具@2025 | version <span id="versionInfo">加载中...</span> | 技术支持 liboi@Servyou.com.cn & wzj@Servyou.com.cn
    </footer>
    <script>
        // 获取并显示版本信息
        document.addEventListener('DOMContentLoaded', function() {
            fetch('/api/version')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('versionInfo').textContent = data.version || '未知版本';
                })
                .catch(error => {
                    console.error('获取版本信息失败:', error);
                    document.getElementById('versionInfo').textContent = '获取失败';
                });
        });
    </script>
</body>
</html>